package org.jdcenter.jndi.context.local;

import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import javax.naming.Name;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RMIJRMPContextServer extends RMIContextServer implements Remote{
	
	private Log log = LogFactory.getLog(getClass());
	
	public RMIJRMPContextServer(){
		
	}
	public RMIJRMPContextServer(int port){
		super(port);
	}
	
	public void start() throws NamingException{
		try {
            UnicastRemoteObject.exportObject(this);
            Naming.bind(url, this);
            log.info(this + " running");
        } catch (RemoteException e) {
            log.error(e);
            throw new NamingException(e.getMessage());
        } catch (MalformedURLException e) {
        	log.error(e);
            throw new NamingException(e.getMessage());
        } catch (AlreadyBoundException e) {
        	log.error(e);
            throw new NamingException(e.getMessage());
        }
	}
	
	public void stop() throws NamingException{
		try {
            Naming.unbind(url);
            UnicastRemoteObject.unexportObject(this, true);
            log.info(this + " closed");
        } catch (RemoteException e) {
            log.error(e);
            throw new NamingException(e.getMessage());
        } catch (MalformedURLException e) {
        	log.error(e);
            throw new NamingException(e.getMessage());
        } catch (NotBoundException e) {
        	log.error(e);
            throw new NamingException(e.getMessage());
		}
	}
	
	public void bind(Name name, Object obj) throws NamingException {
		proxyContext.bind(name, obj);
    }
    
    public void rebind(Name name, Object obj) throws NamingException {
    	proxyContext.rebind(name, obj);
    }
    
    public void unbind(Name name) throws NamingException {
    	proxyContext.unbind(name);
    }
    
    public Object lookup(Name name) throws NamingException {
    	return proxyContext.lookup(name);
    }

}
